package pub.tbc.rubbish.client.factory;

import pub.tbc.rubbish.client.discovery.DefaultDiscovery;
import pub.tbc.rubbish.client.discovery.Discovery;
import pub.tbc.rubbish.client.discovery.ServiceConnection;
import pub.tbc.rubbish.client.discovery.cache.MapCache;
import pub.tbc.rubbish.client.discovery.cache.ServiceCache;
import pub.tbc.rubbish.client.discovery.zk.ZKService;
import pub.tbc.rubbish.client.registry.Registry;
import pub.tbc.rubbish.client.registry.impl.ZKRegistry;
import pub.tbc.toolkit.Objs;

/**
 * @author tbc on 2016/12/13 0:08.
 */
public class ObjectFactory {
    private static ServiceCache serviceCache;
    private static Object serviceCacheLock = new Object();
    private static Discovery discovery;
    private static Object discoveryLock = new Object();
    private static Registry registry;
    private static Object registryLock = new Object();
    private static ServiceConnection serviceConnection;
    private static Object serviceConnectionLock = new Object();


    public static ServiceCache getServiceCache() {
        if (Objs.isEmpty(serviceCache)) {
            synchronized (ObjectFactory.class) {
                if (Objs.isEmpty(serviceCache)) {
                    serviceCache = new MapCache();
                }
            }
        }
        return serviceCache;
    }

    public static Discovery getDiscovery() {
//        return new DefaultDiscovery();
        if (Objs.isEmpty(discovery)) {
            synchronized (ObjectFactory.class) {
                if (Objs.isEmpty(discovery)) {
                    discovery = new DefaultDiscovery();
                }
            }
        }
        return discovery;
    }

    public static Registry getRegistry() {
//        return new ZKRegistry();
        if (Objs.isEmpty(registry)) {
            synchronized (ObjectFactory.class) {
                if (Objs.isEmpty(registry)) {
                    registry = new ZKRegistry();
                }
            }
        }
        return registry;
    }

    public static ServiceConnection getServiceConnection() {
//        return new ZKService();
        if (Objs.isEmpty(serviceConnection)) {
            synchronized (ObjectFactory.class) {
                if (Objs.isEmpty(serviceConnection)) {
                    serviceConnection = new ZKService();
                }
            }
        }
        return serviceConnection;
    }
}
